package com.runen.infinitemovement.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.entity.StartChallengeEntity;
import com.runen.infinitemovement.tool.ActivityAnimationUtil;
import com.runen.infinitemovement.tool.DensityUtil;
import com.runen.infinitemovement.track.recorduitl.BackStageManagementUtil;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class StartSportsActivity extends BaseActivity {
    static final int ANIMATION_DURATION = 300;
    static final int SOUNDPOOL_MAX_STREAMS = 3;
    static final int SOUNDPOOL_LEFT_VOLUME = 1;
    static final int SOUNDPOOL_RIGHT_VOLUME = 1;
    static final int SOUNDPOOL_PRIORITY = 0;
    static final int SOUNDPOOL_LOOP = 0;
    static final int SOUNDPOOL_RATE = 1;
    static final int MSG_IN_ANIMATION = 0x1502;
    static final int MSG_OUT_ANIMATION = 0x1503;
    static final int MSG_PAY_AUDIOS = 0x1504;

    Unbinder unbinder;

    private SoundPool soundPool;
    AnimationHandler animationHandler;
    AnimatorListenerAdapter inAdapter;
    AnimatorListenerAdapter outAdapter;
    Map<Integer, Map<String, Integer>> audios;
    int index;
    @BindView(R.id.iv_num)
    ImageView ivNum;
    private int sportsType;
    private int weatherType;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_start_sports;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        unbinder = ButterKnife.bind(this);
        animationHandler = new AnimationHandler(this);
        initArgs();
        initView();
        initAudio();
        initListener();
        execute();
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearAnimation();
        unbinder.unbind();
        animationHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.REQUEST_CODE_SPORTS_STATUS:
                if (resultCode == Activity.RESULT_OK) {
                    ActivityCompat.finishAfterTransition(this);
                }
                break;
            default:
                break;
        }
    }

    private void initArgs() {
        sportsType = getIntent().getIntExtra("SPORTS_TYPE", 0);
        weatherType = getIntent().getIntExtra("weatherType", 1);
    }

    private void initView() {

    }

    private void initAudio() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(SOUNDPOOL_MAX_STREAMS);
            AudioAttributes.Builder aab = new AudioAttributes.Builder();
            aab.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
            aab.setLegacyStreamType(AudioManager.STREAM_DTMF);
            aab.setUsage(AudioAttributes.USAGE_MEDIA);
            builder.setAudioAttributes(aab.build());
            soundPool = builder.build();
        } else {
            soundPool = new SoundPool(SOUNDPOOL_MAX_STREAMS, AudioManager.STREAM_DTMF, 0);
        }
        audios = new LinkedHashMap<>();
        int[] raws = new int[]{R.raw.n3, R.raw.n2, R.raw.n1};
        for (int index = 0; index < raws.length; index++) {
            Map<String, Integer> audio = new LinkedHashMap<>();
            audio.put("id", soundPool.load(this, raws[index], 0));
            audio.put("duration", getAudioDuration(raws[index]));
            audios.put(index, audio);
        }
    }

    private void initListener() {
        inAdapter = new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                if (3 - index == 1) {
                    ivNum.setImageResource(R.mipmap.ico_1);
                } else if (3 - index == 2) {
                    ivNum.setImageResource(R.mipmap.ico_2);
                    animationHandler.sendEmptyMessage(MSG_PAY_AUDIOS);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(900);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            animationHandler.sendEmptyMessage(MSG_PAY_AUDIOS);
                        }
                    }).start();
                } else if (3 - index == 3) {
                    ivNum.setImageResource(R.mipmap.ico_3);
                    animationHandler.sendEmptyMessage(MSG_PAY_AUDIOS);
                }

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                animationHandler.sendEmptyMessageDelayed(MSG_OUT_ANIMATION, audios.get(index).get("duration"));
            }
        };

        outAdapter = new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                ++index;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (index == audios.size()) {
                    toSportsStatus();
                    return;
                }
                animationHandler.sendEmptyMessage(MSG_IN_ANIMATION);
            }
        };
    }

    /**
     * 执行
     */
    private void execute() {
        animationHandler.sendEmptyMessage(MSG_IN_ANIMATION);
    }

    /**
     * 播放声音
     */
    private void payAudios() {
        soundPool.play(audios.get(index).get("id"),
                SOUNDPOOL_LEFT_VOLUME,
                SOUNDPOOL_RIGHT_VOLUME,
                SOUNDPOOL_PRIORITY,
                SOUNDPOOL_LOOP,
                SOUNDPOOL_RATE);
    }

    /**
     * 进场动画
     */
    private void inAnimator() {
        final ImageView iv = ivNum;
        AnimatorSet animatorSet = new AnimatorSet();
        ValueAnimator alpha = ValueAnimator.ofInt(0, 255);
        alpha.setDuration(ANIMATION_DURATION);
        alpha.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.setImageAlpha(vulue);
                }
            }
        });

        ValueAnimator scale = ValueAnimator.ofInt(0, 179);
        scale.setDuration(ANIMATION_DURATION);
        scale.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.getLayoutParams().height = DensityUtil.dip2px(StartSportsActivity.this, vulue);
                    iv.requestLayout();
                }
            }
        });

        animatorSet.play(alpha);
        animatorSet.play(scale);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.addListener(inAdapter);
        animatorSet.start();
    }

    /**
     * 出场动画
     */
    private void outAnimator() {
        final ImageView iv = ivNum;
        AnimatorSet animatorSet = new AnimatorSet();
        ValueAnimator alpha = ValueAnimator.ofInt(255, 0);
        alpha.setDuration(ANIMATION_DURATION);
        alpha.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.setImageAlpha(vulue);
                }
            }

        });

        ValueAnimator scale = ValueAnimator.ofInt(179, 249);
        scale.setDuration(ANIMATION_DURATION);
        scale.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int vulue = (int) animation.getAnimatedValue();
                if (iv != null) {
                    iv.getLayoutParams().height = DensityUtil.dip2px(StartSportsActivity.this, vulue);
                    iv.requestLayout();
                }
            }
        });

        animatorSet.play(alpha);
        animatorSet.play(scale);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.addListener(outAdapter);
        animatorSet.start();
    }

    /**
     * 清除动画
     */
    private void clearAnimation() {
        ivNum.clearAnimation();
    }

    /**
     * 10进制转化16进制
     *
     * @param value
     * @return
     */
    private String getHexString(int value) {
        String hexString = Integer.toHexString(value);
        if (hexString.length() == 1) {
            hexString = "0" + hexString;
        }
        return hexString;
    }

    /**
     * 获取声音时长
     *
     * @param res
     * @return
     */
    private int getAudioDuration(int res) {
        MediaPlayer mediaPlayer = MediaPlayer.create(this, res);
        return mediaPlayer.getDuration();
    }

    /**
     * 进入运动状态界面
     */
    private void toSportsStatus() {
        Iterator<Map.Entry<Integer, Map<String, Integer>>> entries = audios.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Integer, Map<String, Integer>> entry = entries.next();
            soundPool.stop(entry.getValue().get("id"));
        }
        soundPool.release();

        //生成运动id
//        Intent i = new Intent(Config.ALARM_TRACE_COMMON_ACTION);
//        i.setComponent(new ComponentName(this, CommonReceiver.class));
//        i.putExtra("flag", "1");
//        sendBroadcast(i);
        startSports();


//        ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(this, tvNum, "start");
//        ActivityCompat.startActivity(this, intent, optionsCompat.toBundle());
//        ActivityCompat.finishAfterTransition(SportsStartActivity.this);
    }

    private void startSports() {
        JSONObject object = new JSONObject();
        try {
            object.put("type", sportsType);
            object.put("weather", weatherType);
            object.put("phoneModel", BackStageManagementUtil.getMobileType());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ChallengeAPI().onStartChallenge(object.toString(), new BaseResultCallback<StartChallengeEntity>() {
            @Override
            public void onResponse(StartChallengeEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        Intent intent = new Intent(StartSportsActivity.this, SportsStatusActivity.class);
                        intent.putExtra("SPORTS_TYPE", sportsType);
                        intent.putExtra("sportRecordId", response.data.sportRecordId);
                        ActivityAnimationUtil.startActivityForFinish(StartSportsActivity.this, intent);
                    }
                } else {
                    Intent intent = new Intent(StartSportsActivity.this, SportsStatusActivity.class);
                    intent.putExtra("SPORTS_TYPE", sportsType);
                    intent.putExtra("weather", weatherType);
                    ActivityAnimationUtil.startActivityForFinish(StartSportsActivity.this, intent);
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                Intent intent = new Intent(StartSportsActivity.this, SportsStatusActivity.class);
                intent.putExtra("SPORTS_TYPE", sportsType);
                intent.putExtra("weather", weatherType);
                ActivityAnimationUtil.startActivityForFinish(StartSportsActivity.this, intent);
            }
        });
    }

    private static class AnimationHandler extends Handler {
        private WeakReference<StartSportsActivity> reference;

        private AnimationHandler(StartSportsActivity activity) {
            this.reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            StartSportsActivity activity = reference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case MSG_IN_ANIMATION:
                    activity.inAnimator();
                    break;
                case MSG_OUT_ANIMATION:
                    activity.outAnimator();
                    break;
                case MSG_PAY_AUDIOS:
                    activity.payAudios();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
